import { Injectable, Inject, ElementRef } from "@angular/core";
import {
  AsyncValidator,
  NG_ASYNC_VALIDATORS,
  ValidationErrors,
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
  ControlValueAccessor,
  NG_VALUE_ACCESSOR,
  FormControl
} from "@angular/forms";

interface IAccount {
  username: string;
  password: string;
}

@Injectable({
  providedIn: "root"
})
export class AccountService {
  validateForm: FormGroup;
  constructor(@Inject("CookieService") private cookieService) {}
  init(validateForm: FormGroup) {
    this.validateForm = validateForm;

    this.addListen();

    const isRememberAccount: boolean = this.getIsRememberAccount();

    // update account on init from cookie
    this.validateForm.controls.remember.setValue(isRememberAccount);
  }

  getIsRememberAccount(): boolean {
    const b = this.cookieService.get("isRememberAccount");
    return b === "true" ? true : false;
  }

  addListen() {
    // when click remember account
    this.validateForm.controls.remember.valueChanges.subscribe(e => {
      // update cookie with isRememberAccount from user operation
      this.cookieService.put("isRememberAccount", e);
      if (e) {
        const account = this.getAccount();
        this.fillAccount(account);
        return;
      }
      this.doFogot();
    });

    // this.validateForm.valueChanges.subscribe(e => {
    //   const isRememberAccount: boolean = this.getIsRememberAccount();
    //   if (isRememberAccount) {
    //     this.doRemember();
    //   }
    // });
    this.validateForm.valueChanges.subscribe(e => {
      this.doRemember();
    });
  }

  fillAccount(account: IAccount) {
    this.validateForm.controls.username.setValue(account.username);
    this.validateForm.controls.password.setValue(account.password);
  }

  onClickRemember(b: boolean) {
    if (b) {
      this.doRemember();
      return;
    }
    this.doFogot();
  }

  private getAccountFromValidateForm() {
    const account: IAccount = {
      username: this.validateForm.controls.username.value,
      password: this.validateForm.controls.password.value
    };
    return account;
  }

  private doRemember(): void {
    this.cookieService.putObject("account", this.getAccountFromValidateForm());
  }

  private doFogot(): void {
    this.cookieService.remove("account");
    this.cookieService.remove("isRememberAccount");
  }

  private hasAccount(): boolean {
    const account: IAccount = this.getAccount();
    if (!!account) {
      return true;
    }
    return false;
  }

  public getAccount(): IAccount {
    const account = this.cookieService.getObject("account");
    if (!!account) {
      return account;
    }
    return { username: "", password: "" };
  }
}
